package cn.jyszn.wxb.service;

import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.jyszn.wxb.dao.UserInfoMapper;
import cn.jyszn.wxb.model.UserInfo;

@Service
public class UserInfoService {
	
	private Logger logger = LogManager.getLogger(this.getClass());
	
	@Autowired
	private UserInfoMapper userInfoMapper;
	
	public boolean add(UserInfo userInfo){
		boolean flag = false;
		logger.info("开始插入数据：" + userInfo);
		userInfoMapper.updateAllLeftNum(userInfo.getRightNum());
		userInfoMapper.updateAllRightNum(userInfo.getLeftNum());
		int result = userInfoMapper.insert(userInfo);
		if(result == 1){
			logger.info("插入数据：成功|" + userInfo);
			flag = true;
		}else{
			logger.info("插入数据：失败|" + userInfo);
		}
		return flag;
	}

	public UserInfo load(Long phone, String password){
		return userInfoMapper.selectForLogin(phone, password);
	}

	public UserInfo load(int id){
		return userInfoMapper.selectByPrimaryKey(id);
	}
	
	public JSONObject load(String belongCode, int page, int rows, long startTimeStamp, long endTimeStamp){
		JSONObject resultJson = new JSONObject();
		int size = rows > 0 ? rows : 10;
		int start = page >= 1 ? (page - 1)* size : -1;
		List<UserInfo> userInfos = userInfoMapper.selectByBelongCode(belongCode, start, size, startTimeStamp, endTimeStamp);
		resultJson.put("rows", userInfos);
		int total = userInfoMapper.totalByBelongCode(belongCode, startTimeStamp, endTimeStamp);
		resultJson.put("total", total);
		return resultJson;
	}
	
	public JSONObject load(int id, int level, int page, int rows, long startTimeStamp, long endTimeStamp){
		JSONObject resultJson = new JSONObject();
		int size = rows > 0 ? rows : 10;
		int start = page >= 1 ? (page - 1)* size : -1;
		List<UserInfo> userInfos = userInfoMapper.selectChildNodeById(id, level, 2, start, rows, startTimeStamp, endTimeStamp);
		resultJson.put("rows", userInfos);
		int total = userInfoMapper.totalChildNodeById(id, level, 2, startTimeStamp, endTimeStamp);
		resultJson.put("total", total);
		return resultJson;
	}

	/**
	 * 根据id更新用户的状态
	 * @param id
	 * @param status
	 * @return
	 */
	public boolean update(int id, int status){
		UserInfo user = userInfoMapper.selectByPrimaryKey(id);
		if(user == null){
			return false;
		}
		user.setStatus((short) status);
		int result = userInfoMapper.updateByPrimaryKeySelective(user);
		if(result == 1){
			logger.info("更新状态成功: ststus=" + status);
			return true;
		}
		logger.info("更新状态失败: ststus=" + status);
		return false;
	}
	
}
